<?php
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/27
 */

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 用户余额日志模型
 */
class UserBalanceLogModel extends BaseModel
{
    protected $tableName = 'user_balance_log';

    /**
     * 记录额度转换日志
     * @param  [type] $userId  用户ID
     * @param  [type] $orderBn 订单号
     * @param  [type] $balance 余额
     * @param  [type] $change  变更金额
     * @return boolean         
     */
    public function writeRechargeLog($userId, $orderBn, $balance, $change)
    {
    	$data = [
    		'user_id' => $userId,
    		'order_bn' => $orderBn,
    		'balance' => $balance,
    		'change' => $balance,
            'log_type' => 'recharge',
    	];

    	return parent::save($data);
    }

    /**
     * 额度转换
     * @param  string $orderBn 订单号
     * @param  string $type     in: 转入 out: 转出
     * @return array           前后余额
     */
    public function recharge($orderBn, $money, $userId = 0, $type = 'in')
    {
        $money = floatval($money);
        $lastBalance = $this->chkeckRecharge($orderBn);
        $curBalance = 0;

        if ($type == 'in'){
            $curBalance = $lastBalance + $money;
        } else if ($type == 'out'){
            $curBalance = $lastBalance - $money;
        } else {
            return false;
        }

        $data = [
            'user_id' => $userId ? intval($userId) : session('user.id'),
            'order_bn' => $orderBn,
            'log_type' => 'recharge',
            'balance' => $balance,
            'change' => $curBalance - $lastBalance,
        ];

        $result = parent::save($data);
        if ($result){
            return [
                'oMoney' => $lastBalance,
                'cMoney' => $curBalance,
                ];
        }

        return false;
    }

    /**
     * 额度转换状态查询
     * @param  [type] $orderBn 订单号
     * @return float           余额
     */
    public function chkeckRecharge($orderBn, $userId = 0)
    {
        $where = [
            'user_id' => $userId ? $userId : session('user.id'),
            'order_bn' => $orderBn,
            ];
        $result = $this->getRow($where, 'balance');

        return ['money' => $result['balance']];
    }

}